import { DiagnosticService } from './diagnosticService';
import { WorkspaceDiagnosticService } from './workspaceDiagnosticService';
import { useProblemsStore } from '../stores/problems';

/**
 * 统一诊断服务管理器
 * 
 * 设计思路（参考VS Code）：
 * 1. 双层诊断系统：
 *    - Monaco层：实时诊断打开的文件（类似VS Code的编辑器诊断）
 *    - 工作区层：后台诊断所有文件（类似VS Code的Language Server诊断）
 * 
 * 2. 优先级策略：
 *    - 已打开文件：优先使用Monaco实时诊断
 *    - 未打开文件：使用工作区诊断缓存
 * 
 * 3. 性能优化：
 *    - 增量更新：只更新变化的部分
 *    - 防抖处理：避免频繁更新
 *    - 批量处理：减少UI更新频率
 */
export class DiagnosticManager {
  private static _instance: DiagnosticManager | null = null;
  private monacoService: DiagnosticService;
  private workspaceService: WorkspaceDiagnosticService;
  private updateTimer: number | null = null;
  private _problems: any = null;

  private get problems() {
    if (!this._problems) {
      try {
        this._problems = useProblemsStore();
      } catch (error) {
        console.warn('Problems store not available yet');
        return null;
      }
    }
    return this._problems;
  }

  static get instance(): DiagnosticManager {
    if (!this._instance) {
      this._instance = new DiagnosticManager();
    }
    return this._instance;
  }

  constructor() {
    this.monacoService = DiagnosticService.instance;
    this.workspaceService = WorkspaceDiagnosticService.instance;
    this.setupIntegration();
    
    // 延迟启动工作区扫描
    this.scheduleInitialScan();
  }

  /**
   * 延迟启动初始扫描
   */
  private scheduleInitialScan() {
    // 增加延迟时间，给工作区索引器更多时间完成索引
    setTimeout(async () => {
      try {
        // 检查工作区索引器状态
        const { workspaceIndexer } = await import('./WorkspaceIndexer.ts');
        
        if (workspaceIndexer.isIndexing.value) {
          console.log('[DiagnosticManager] Workspace indexer still running, waiting...');
          // 如果索引器还在运行，再等待一下
          setTimeout(async () => {
            try {
              // 检查诊断服务是否已经在运行
              if (this.workspaceService.isScanning.value) {
                console.log('[DiagnosticManager] Diagnostic service already running, skipping delayed scan');
                return;
              }
              
              console.log('[DiagnosticManager] Starting delayed workspace diagnostic scan');
              await this.workspaceService.startFullScan();
              console.log('[DiagnosticManager] Delayed workspace scan completed');
            } catch (error) {
              console.warn('[DiagnosticManager] Delayed workspace scan failed:', error);
            }
          }, 3000); // 再等待3秒
        } else {
          // 检查诊断服务是否已经在运行
          if (this.workspaceService.isScanning.value) {
            console.log('[DiagnosticManager] Diagnostic service already running, skipping initial scan');
            return;
          }
          
          console.log('[DiagnosticManager] Starting initial workspace diagnostic scan');
          await this.workspaceService.startFullScan();
          console.log('[DiagnosticManager] Initial workspace scan completed');
        }
      } catch (error) {
        console.warn('[DiagnosticManager] Initial workspace scan failed:', error);
      }
    }, 8000); // 增加到8秒延迟，确保索引器先完成
  }

  /**
   * 设置集成逻辑
   */
  private setupIntegration() {
    // 重写Monaco服务的collectProblems方法，让它通知管理器
    const originalCollectProblems = this.monacoService.collectProblems.bind(this.monacoService);
    this.monacoService.collectProblems = () => {
      originalCollectProblems();
      this.scheduleUpdate();
    };

    console.log('DiagnosticManager initialized with integrated services');
  }

  /**
   * 调度更新（防抖处理）
   */
  private scheduleUpdate() {
    if (this.updateTimer) {
      clearTimeout(this.updateTimer);
    }
    
    this.updateTimer = window.setTimeout(() => {
      this.updateUnifiedProblems();
    }, 100); // 较短的防抖时间，保持响应性
  }

  /**
   * 更新统一的问题列表
   */
  private updateUnifiedProblems() {
    try {
      const monacoProblems = this.getMonacoProblems();
      const workspaceProblems = this.getWorkspaceProblems();
      
      // 合并诊断信息
      const mergedProblems = this.mergeProblems(monacoProblems, workspaceProblems);
      
      // 更新问题存储
      const problemsStore = this.problems;
      if (problemsStore) {
        problemsStore.set(mergedProblems);
      }

      // 输出诊断统计
      this.logDiagnosticsStats(mergedProblems);

    } catch (error) {
      console.error('Failed to update unified problems:', error);
    }
  }

  /**
   * 获取Monaco诊断问题（已打开文件的实时诊断）
   */
  private getMonacoProblems() {
    const problemsStore = this.problems;
    if (!problemsStore) return [];

    // Monaco服务已经更新了store，直接获取
    return problemsStore.items || [];
  }

  /**
   * 获取工作区诊断问题（未打开文件的缓存诊断）
   */
  private getWorkspaceProblems() {
    // 从工作区服务获取缓存的诊断信息
    const workspaceProblems = [];
    const diagnosticsCache = this.workspaceService['diagnosticsCache'];
    
    if (diagnosticsCache) {
      for (const [filePath, diagnostics] of diagnosticsCache.entries()) {
        workspaceProblems.push(...diagnostics);
      }
    }

    return workspaceProblems;
  }

  /**
   * 合并问题列表
   * 策略：Monaco诊断优先（实时且准确），工作区诊断补充（覆盖面广）
   */
  private mergeProblems(monacoProblems: any[], workspaceProblems: any[]) {
    // 获取Monaco诊断覆盖的文件
    const monacoFiles = new Set(monacoProblems.map(p => p.file));
    
    // 过滤工作区诊断：排除已被Monaco覆盖的文件
    const filteredWorkspaceProblems = workspaceProblems.filter(p => 
      !monacoFiles.has(p.file)
    );

    // 合并结果：Monaco诊断 + 未覆盖文件的工作区诊断
    return [...monacoProblems, ...filteredWorkspaceProblems];
  }

  /**
   * 输出诊断统计信息
   */
  private logDiagnosticsStats(problems: any[]) {
    const stats = {
      total: problems.length,
      errors: problems.filter(p => p.severity === 'error').length,
      warnings: problems.filter(p => p.severity === 'warning').length,
      info: problems.filter(p => p.severity === 'info').length,
      files: new Set(problems.map(p => p.file)).size
    };

    console.log(`[DiagnosticManager] Updated problems: ${stats.total} total (${stats.errors} errors, ${stats.warnings} warnings, ${stats.info} info) across ${stats.files} files`);
  }

  /**
   * 手动触发完整更新
   */
  async refreshAll() {
    console.log('[DiagnosticManager] Performing full refresh...');
    
    // 重新收集Monaco诊断
    this.monacoService.collectProblems();
    
    // 重新扫描工作区
    await this.workspaceService.startFullScan();
    
    // 立即更新
    this.updateUnifiedProblems();
  }

  /**
   * 取消工作区扫描
   */
  cancelWorkspaceScan() {
    this.workspaceService.cancelScan();
  }

  /**
   * 获取诊断模式信息
   */
  getDiagnosticModes() {
    return {
      monaco: {
        enabled: true,
        description: '实时诊断已打开的文件',
        coverage: 'opened-files'
      },
      workspace: {
        enabled: true,
        description: '后台诊断工作区所有文件', 
        coverage: 'workspace-wide'
      }
    };
  }

  /**
   * 获取详细统计信息
   */
  getDetailedStats() {
    const monacoProblems = this.getMonacoProblems();
    const workspaceProblems = this.getWorkspaceProblems();
    const workspaceStats = this.workspaceService.getWorkspaceDiagnosticsStats();

    return {
      monaco: {
        problems: monacoProblems.length,
        files: new Set(monacoProblems.map((p: any) => p.file)).size
      },
      workspace: workspaceStats,
      total: {
        problems: monacoProblems.length + workspaceProblems.length,
        uniqueFiles: new Set([
          ...monacoProblems.map((p: any) => p.file),
          ...workspaceProblems.map(p => p.file)
        ]).size
      }
    };
  }

  /**
   * 清理服务
   */
  dispose() {
    if (this.updateTimer) {
      clearTimeout(this.updateTimer);
      this.updateTimer = null;
    }

    this.monacoService.dispose();
    this.workspaceService.dispose();
    DiagnosticManager._instance = null;
  }
}

// 导出获取单例实例的函数
export const getDiagnosticManager = () => DiagnosticManager.instance;